package com.authine.cloudpivot.ext.applicationservice.authority;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.Exceptions;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.organization.UserApi;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.enums.system.ResourceTypeEnum;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.Operator;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName UserTabsService
 * @Description: 获取用户标签页信息
 * @Author fj
 * @Date 2021/9/26
 * @Version V1.0
 **/
@Path("UserTabsService")
@Slf4j
public class UserTabsService {
    private static final UserApi userApi = new UserApi();

    /**
     * 通过应用编码和页面编码获取用户标签页数据
     *
     * @return 树形列表
     */
    @Path("getUserTabsByAppCodeAndPageCode")
    @POST
    @Operation(summary = "通过应用编码和页面编码获取用户标签页数据", tags = CUSTOM_SERVICE)
    public SingleResponse<List<String>> getUserTabsByAppCodeAndPageCode(@Parameter SaveOrUpdateBO param) {
        Assert.notNull(param.getData().get("appCode"), "应用编码不能为空");
        Assert.notNull(param.getData().get("pageCode"), "页面编码不能为空");

        // 根据角色id查询角色资源
        UserDto user = UserTabsService.userApi.getUserByIdThroughJDBC(UserDto.builder().id(RequestContext.getCorpLoginId()).build());

        if (StringUtils.isEmpty(user.getRole_ids())) {
            Exceptions.throwBizException(ErrorCodeEnum.ILLEGAL_PERMISSION_DATA);
        }
        List<String> roleIdList = Arrays.asList(user.getRole_ids().split(","));

        // 通过角色id获取角色权限列表
        SingleResponse<BOList> roleResourceBOList = BoServiceUtils.findListByIn(ModelConst.T_ROLE_RESOURCE, "role_id", roleIdList);
        log.info("------------------------通过角色id获取角色权限列表：{}------------------------", JSONObject.toJSONString(roleResourceBOList));

        // 获取资源id
        List<Object> resourceIDList = roleResourceBOList.getData().getData()
                .stream()
                .map(roleResource -> roleResource.get("resource"))
                .distinct()
                .collect(Collectors.toList());

        // 通过资源id、应用编码、页面编码、类型获取标签页信息
        String[] columnNames = new String[]{"id", "type", "appCode", "pageCode"};
        Operator[] operators = new Operator[]{Operator.IN, Operator.EQ, Operator.EQ, Operator.EQ};
        Object[] columnValues = new Object[]{resourceIDList, ResourceTypeEnum.TABS.getCode(), param.getData().get("appCode"), param.getData().get("pageCode")};
        SingleResponse<BOList> resourceBOList = BoServiceUtils.findListByComplex(ModelConst.T_RESOURCE, columnNames, columnValues, operators);
        log.info("------------------------通过查询条件获取资源id列表：{}------------------------", JSONObject.toJSONString(roleResourceBOList));
        if (resourceBOList.getData().getTotal() == 0) {
            return SingleResponse.of(Lists.newArrayList());
        } else {
            List<String> tabs = resourceBOList.getData().getData().stream().map(resource -> String.valueOf(resource.get("componentCode"))).collect(Collectors.toList());
            return SingleResponse.of(tabs);
        }
    }
}
